//
//  MarketingViewController.m
//  EMMApp
//
//  Created by Mac on 16/6/30.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "MarketingViewController.h"

/** ViewController
 *
 *  ViewController导入.h文件
 */
#import "HousingDetailsViewController.h"

/** Cell
 *
 *  Cell导入.h文件
 */
#import "NewCustomersCell.h"
#import "MarketingCell.h"
#import "MarketingOneCell.h"
#import "MarketingTwoCell.h"
#import "HousingCVCell.h"

/** Api
 *
 *  Api调用导入.h文件
 */
#import "GetMarketingControlListApi.h"

@interface MarketingViewController ()<UITableViewDataSource,UITableViewDelegate,MarketingTwoCellDelegate>

/**
 *  创建UITableView 命名:marketingTableView
 */
@property (nonatomic, strong) UITableView *marketingTableView;

/**
 *  二级列表是否展开状态
 */
@property (nonatomic, strong) NSMutableArray *selectedArr;

/**
 *  数据源数组
 */
@property (nonatomic, strong) NSMutableArray *unitList;

/**
 *  GetMarketingControlList - model
 */
@property (nonatomic, strong) GetMarketingControlList *getMarketingControlList;

/**
 *  分区0 数据源数组
 */
@property (nonatomic, strong) NSMutableArray *buildingStatusList;

/**
 *  分区1 数据源数组
 */
@property (nonatomic, strong) NSMutableArray *subDataArr;

@end

@implementation MarketingViewController

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    _buildingStatusList = [[NSMutableArray alloc] init];
    _unitList = [[NSMutableArray alloc] init];
    _subDataArr = [[NSMutableArray alloc] init];
    [self postGetHousesListApi];
    [self creatNavigationController];
    _selectedArr = [NSMutableArray arrayWithObjects:@"0",nil];
    _marketingTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH,EMM_HEIGHT-SafeAreaTopHeight) style:UITableViewStyleGrouped];
    _marketingTableView.delegate = self;
    _marketingTableView.dataSource = self;
    _marketingTableView.showsVerticalScrollIndicator = NO;
    _marketingTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_marketingTableView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

#pragma mark - 导航
/**
 *  功能描述：
 *  导航初始化
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)creatNavigationController {
    NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
    NSString *token = [userdf objectForKey:@"is_login"];
    NSString *projectName;
    if ([NSString isStringEmpty2:token] == NO) {
        projectName  = [userdf objectForKey:@"projectName"];
    }
    [self updateNavBar];
    self.navigationItem.title = projectName;
    [self configLeftBtn];
}

#pragma mark - 房源数据请求
/**
 *  功能描述：
 *  房源房号列表的Api请求数据调用方法
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 *  
 *  修改时间：2016/12/30
 *  修改人： wangguiping
 */
- (void)postGetHousesListApi {
    [self showHudInWindow:@"正在请求稍等......"];
    GetMarketingControlListApi *api = [[GetMarketingControlListApi alloc] initWithPremisesId:_premisesId buildingId:_buildingId];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetMarketingControlListApi *result = (GetMarketingControlListApi *)request;
        if (result.isSuccess) {
            GetMarketingControlList *get = result.resultData;
            _getMarketingControlList = get;
            for (UnitList *list in get.unitList) {
                [_unitList addObject:list];
                NSMutableArray *arr = [[NSMutableArray alloc] init];
                for (FloorList *bList in list.floorList) {
                    NSMutableArray *arr1 = [[NSMutableArray alloc] init];
                    for (RoomList *rlist in bList.roomList) {
                        [arr1 addObject:rlist];
                    }
                    [arr addObject:arr1];
                }
                [_subDataArr addObject:arr];
            }
            for (BuildingStatusList *list in get.buildingStatusList) {
                [_buildingStatusList addObject:list];
            }
        } else {
//            [self showToast:result.resultData.errorMsg];
            NSUserDefaults *userdf = [NSUserDefaults standardUserDefaults];
            NSString *projectCode = [userdf objectForKey:@"projectCode"];
            if ([NSString isStringEmpty2:projectCode] == NO) {
                [self showToast:result.resultData.errorMsg];
            }
            
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_marketingTableView reloadData];
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

#pragma mark----tableViewDelegate
/**
 *  功能描述：
 *  UITabelView 代理方法
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
//返回几个表头
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _unitList.count + 1;
}

//每一个表头下返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString *string = [NSString stringWithFormat:@"%ld",section];
    if (section == 0) {
        if ([_selectedArr containsObject:string]) {
            return 1;
        }else {
            return 0;
        }
    }
    return 1;
}

//设置表头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50;
}

//Section Footer的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.001;
}

//设置view，将替代titleForHeaderInSection方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
        view.backgroundColor = [UIColor colorFromHexCode:@"#fff5e9"];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
        if ([NSString isStringEmpty2:_getMarketingControlList.premisesName] == NO) {
             titleLabel.text = [NSString stringWithFormat:@"%@-%@",_getMarketingControlList.premisesName,_getMarketingControlList.buildingName];
        }else {
             titleLabel.text = @"";
        }
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor colorFromHexCode:@"#1A1A1A"];
        titleLabel.font = [UIFont systemFontOfSize:16];
        [view addSubview:titleLabel];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0, 0, EMM_WIDTH, 50);
        button.tag = 100+section;
        [button addTarget:self action:@selector(doButton:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];
        UIImageView *upImageView = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-40, 20, 20, 10)];
        [view addSubview:upImageView];
        NSString *string = [NSString stringWithFormat:@"%ld",section];
        if ([_selectedArr containsObject:string]) {
            upImageView.image = [UIImage imageNamed:@"sanjt_down"];
        }else {
            upImageView.image = [UIImage imageNamed:@"sanjt_up"];
        }
        return view;
    }
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
    headView.backgroundColor = [UIColor whiteColor];
    UIImageView *vie1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 0.5)];
    vie1.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    [headView addSubview:vie1];
    UIImageView *vie2 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 49.5, EMM_WIDTH, 0.5)];
    vie2.backgroundColor = [UIColor colorFromHexCode:@"#CCCCCC"];
    [headView addSubview:vie2];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 50)];
    UnitList *list = [_unitList objectAtIndex:section-1];
    titleLabel.text = list.unitName;
    titleLabel.textColor = [UIColor colorFromHexCode:@"#1A1A1A"];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [UIFont systemFontOfSize:15];
    [headView addSubview:titleLabel];
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        float h = _buildingStatusList.count/2.00;
        return 30*ceilf(h);
    }
    return 50.f * [_subDataArr[indexPath.section-1] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *indexStr = [NSString stringWithFormat:@"%ld",indexPath.section];
    if ([indexStr isEqualToString:@"0"]) {
        static NSString *CellIdentifier = @"MarketingOneCell";
        MarketingOneCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"MarketingOneCell" owner:self options:nil] lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell initWithMarketingOneCellArray:_buildingStatusList];
        return cell;
    }
    static NSString *CellIdentifier = @"MarketingTwoCell";
    MarketingTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MarketingTwoCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
    cell.delegate = self;
    NSArray *roomList = _subDataArr[indexPath.section-1];
    [cell initWithNSMutableArray:roomList indexNum:indexPath.row];
    [cell setMarketingBlock:^(NSString *roomId) {
        [self cratRoomId:roomId];
    }];
    return cell;
}

#pragma mark - 二级列表是否展开触发方法
/**
 *  功能描述：
 *  二级列表展开收起功能
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
-(void)doButton:(UIButton *)sender {
    NSString *string = [NSString stringWithFormat:@"%ld",sender.tag-100];
    //数组selectedArr里面存的数据和表头想对应，方便以后做比较
    if ([_selectedArr containsObject:string]) {
        [_selectedArr removeObject:string];
    }else {
        [_selectedArr addObject:string];
    }
    [_marketingTableView reloadData];
}

#pragma mark - 获取房号并跳转界面
/**
 *  功能描述：
 *  点击显示房号按钮跳转到详情功能
 *  更新时间：2016/12/22
 *  更新人：wangguiping
 */
- (void)cratRoomId:(NSString *)roomId {
    HousingDetailsViewController *evc = [[HousingDetailsViewController alloc] init];
    evc.roomId = roomId;
    [self.navigationController pushViewController:evc animated:YES];
}

#pragma mark -MarketingTwoCellDelegate 代理调用方法
- (void)marketingTwoCelldidSelectedTableview:(NSInteger)index withcollecttion:(NSIndexPath *)collectionindex {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    RoomList *rlist = [arr objectAtIndex:collectionindex.row];
    HousingDetailsViewController *evc = [[HousingDetailsViewController alloc] init];
    evc.roomId = rlist.roomId;
    [self.navigationController pushViewController:evc animated:YES];
}

@end
